import axios from 'axios'
import qs from 'qs'
import router from '@/router/index'
import { Toast,Dialog  } from 'vant';
import {domain_name} from './config';
Toast.setDefaultOptions({ duration: 2000 });

let cancel, promiseArr = {};
const CancelToken = axios.CancelToken;
var myaxios = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: domain_name,
});
// axios.defaults.withCredentials = true;
//请求拦截器
// myaxios.interceptors.request.use(config => {  
  //发起请求时，取消掉当前正在进行的相同请求
  // if (promiseArr[config.url]) {
  //   promiseArr[config.url]('操作取消');
  //   promiseArr[config.url] = cancel;
  // } else {
  //   promiseArr[config.url] = cancel;
  // }
//   return config;
// }, error => {
//   return Promise.reject(error)
// })

//响应拦截器即异常处理
myaxios.interceptors.response.use(response => {
  return response
}, err => {
  console.log(err);
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '错误请求'
        break;
      case 401:
        err.message = '未授权，请重新登录'
        break;
      case 403:
        err.message = '拒绝访问'
        break;
      case 404:
        err.message = '请求错误,未找到该资源'
        break;
      case 405:
        err.message = '请求方法未允许'
        break;
      case 408:
        err.message = '请求超时'
        break;
      case 500:
        err.message = '服务器端出错'
        break;
      case 501:
        err.message = '网络未实现'
        break;
      case 502:
        err.message = '网络错误'
        break;
      case 503:
        err.message = '服务不可用'
        break;
      case 504:
        err.message = '网络超时'
        break;
      case 505:
        err.message = 'http版本不支持该请求'
        break;
      default:
        err.message = `连接错误${err.response.status}`
    }
  } else {
    err.message = "连接到服务器失败"
  }
  Toast.fail(err.message)

  return Promise.resolve(err.response)
});

function Client (method, action, params, callback, failback, options) {
  // axios传递的请求参数是json格式
  // 如果后端接口要求formData,则post传参是要序列化 qs.stringify(params);
    var default_options = {
      method: method,
      // url: process.env.BASE_API + action,
      url: action,
      data: method === 'post' || method === 'put' ? params : null,
      params: method === 'get' || method === 'delete' ?  params : null,
      timeout: 15000,
      dataType: 'json',
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    };
    var token = localStorage.getItem('agencyToken');
    // 如果存在token，在请求头设置token
    if (token) {
      default_options.headers = {Authorization : 'Bearer ' + token};
    }

    // 扩展参数
    var new_options;
    let opt = options;
    if(typeof(callback) == 'object'){
      opt = callback;
    }
    if (opt) {
      new_options = Object.assign({}, default_options, opt);
    } else {
      new_options = default_options;
    }

    // 请求
    return new Promise((resolve, reject) => {
      const toastLoading = Toast.loading({message: '加载中...',forbidClick: true,});
      myaxios(new_options).then(response => {
        toastLoading.clear();
        let {code, msg} = response.data;     
        if (code == 200) {
          resolve( response.data);
          if(typeof(callback) === 'function'){
            callback( response.data, msg);
          }          
        } else if (code == 401) {
          // Toast.fail('登录失效，请重新登录！');
          Dialog.alert({
            title: '登录失效，请重新登录！',
            message: msg,
          }).then(() => {
            localStorage.clear();
            // router.push({path: '/login'});
            window.location.href = 'http://www.lggcp.com/agency/index.html';
          });          
          return;
        } else if(code == 403){
          Dialog.alert({
            title: '提示',
            message: msg,
          }).then(() => {
            // on close
          });
          faileback(msg);
          return;
        } else {
          Toast.fail(msg || '请求失败！');
          if (typeof(failback) === 'function') {
            failback(msg);
          }
          // return;
        }
      }).catch(error => {
        // Toast.fail(error);
        if (typeof(failback) === 'function') {
          failback(error);
        }
        reject(error);
        return;
      })
    });
}

export default Client;